package com.yupi.yuoj.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.yuoj.annotation.AuthCheck;
import com.yupi.yuoj.common.BaseResponse;
import com.yupi.yuoj.common.DeleteRequest;
import com.yupi.yuoj.common.ErrorCode;
import com.yupi.yuoj.common.ResultUtils;
import com.yupi.yuoj.constant.UserConstant;
import com.yupi.yuoj.exception.BusinessException;
import com.yupi.yuoj.exception.ThrowUtils;
import com.yupi.yuoj.model.entity.AdminLogs;
import com.yupi.yuoj.service.AdminLogsService;
import com.yupi.yuoj.service.UserService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * 管理员日志接口
 *
 * @author yupi
 */
@RestController
@RequestMapping("/admin-logs")
@Slf4j
public class AdminLogsController {

    @Resource
    private AdminLogsService adminLogsService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建管理员日志
     *
     * @param adminLogs
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addAdminLog(@RequestBody AdminLogs adminLogs, HttpServletRequest request) {
        if (adminLogs == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = adminLogsService.save(adminLogs);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newAdminLogId = adminLogs.getId();
        return ResultUtils.success(newAdminLogId);
    }

    /**
     * 删除管理员日志
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteAdminLog(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        // 判断是否存在
        AdminLogs oldAdminLog = adminLogsService.getById(id);
        ThrowUtils.throwIf(oldAdminLog == null, ErrorCode.NOT_FOUND_ERROR);
        boolean b = adminLogsService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新管理员日志（仅管理员）
     *
     * @param adminLogs
     * @param request
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateAdminLog(@RequestBody AdminLogs adminLogs, HttpServletRequest request) {
        if (adminLogs == null || adminLogs.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 判断是否存在
        AdminLogs oldAdminLog = adminLogsService.getById(adminLogs.getId());
        ThrowUtils.throwIf(oldAdminLog == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = adminLogsService.updateById(adminLogs);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取管理员日志
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<AdminLogs> getAdminLogById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        AdminLogs adminLog = adminLogsService.getById(id);
        if (adminLog == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(adminLog);
    }

    /**
     * 分页获取管理员日志列表（仅管理员）
     *
     * @param current
     * @param size
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<AdminLogs>> listAdminLogByPage(@RequestParam long current, @RequestParam long size) {
        Page<AdminLogs> adminLogPage = adminLogsService.page(new Page<>(current, size));
        return ResultUtils.success(adminLogPage);
    }

    /**
     * 根据管理员ID获取日志列表
     *
     * @param adminId
     * @param current
     * @param size
     * @return
     */
    @GetMapping("/list/by-admin")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<AdminLogs>> getLogsByAdminId(
            @RequestParam Integer adminId,
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size) {
        if (adminId == null || adminId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Page<AdminLogs> adminLogsPage = adminLogsService.lambdaQuery()
                .eq(AdminLogs::getAdmin_id, adminId)
                .orderByDesc(AdminLogs::getCreated_at)
                .page(new Page<>(current, size));
        return ResultUtils.success(adminLogsPage);
    }

    /**
     * 根据操作类型获取日志列表
     *
     * @param action
     * @param current
     * @param size
     * @return
     */
    @GetMapping("/list/by-action")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<AdminLogs>> getLogsByAction(
            @RequestParam String action,
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size) {
        if (action == null || action.trim().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Page<AdminLogs> adminLogsPage = adminLogsService.lambdaQuery()
                .eq(AdminLogs::getAction, action)
                .orderByDesc(AdminLogs::getCreated_at)
                .page(new Page<>(current, size));
        return ResultUtils.success(adminLogsPage);
    }

    /**
     * 根据时间范围获取日志列表
     *
     * @param startTime
     * @param endTime
     * @param current
     * @param size
     * @return
     */
    @GetMapping("/list/by-time")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<AdminLogs>> getLogsByTimeRange(
            @RequestParam String startTime,
            @RequestParam String endTime,
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size) {
        if (startTime == null || endTime == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Page<AdminLogs> adminLogsPage = adminLogsService.lambdaQuery()
                .between(AdminLogs::getCreated_at, startTime, endTime)
                .orderByDesc(AdminLogs::getCreated_at)
                .page(new Page<>(current, size));
        return ResultUtils.success(adminLogsPage);
    }

    /**
     * 批量删除管理员日志
     *
     * @param ids
     * @param request
     * @return
     */
    @PostMapping("/batch/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> batchDeleteAdminLogs(@RequestBody List<Long> ids, HttpServletRequest request) {
        if (ids == null || ids.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = adminLogsService.removeByIds(ids);
        return ResultUtils.success(result);
    }

    /**
     * 清理指定天数前的日志
     *
     * @param days
     * @param request
     * @return
     */
    @PostMapping("/clean")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> cleanOldLogs(@RequestParam Integer days, HttpServletRequest request) {
        if (days == null || days <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 这里需要根据具体的数据库实现来清理指定天数前的日志
        // 示例：删除30天前的日志
        boolean result = adminLogsService.lambdaUpdate()
                .lt(AdminLogs::getCreated_at, 
                    java.time.LocalDateTime.now().minusDays(days))
                .remove();
        return ResultUtils.success(result);
    }

}